package com.wanlian.fileserver.device.Handler;

import com.wanlian.fileserver.device.worker.DeviceServerFileWorker;
import com.wanlian.netty.File.msg.FilePeerMsg;
import com.wanlian.netty.File.msg.FilePeerMsgQueue;
import com.wanlian.netty.model.Session;
import com.wanlian.netty.msg.MsgType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Handles a server-side channel.
 */
public class DeviceServerFileHandler extends ChannelInboundHandlerAdapter { // (1)
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        try {
            FilePeerMsg filePeerMsg = (FilePeerMsg) msg;
            String msgType= filePeerMsg.getFileBaseMsg().getType();

            String clientId = filePeerMsg.getFileBaseMsg().getBaseHead().getClientId();
            Session oldSession= DeviceServerFileWorker.sessionPool.getSessionByPublicKey(clientId);

            if(oldSession!=null){
                Session session = new Session(ctx.channel());
                session.setId(ctx.channel().id());
                session.setPublicKey(clientId);
                DeviceServerFileWorker.sessionPool.changeSession(session);
            }else{
                Session session = new Session(ctx.channel());
                session.setId(ctx.channel().id());
                session.setPublicKey(clientId);
                DeviceServerFileWorker.sessionPool.addSession(session);
            }
            if(!msgType.equals(MsgType.DEVICE_FILE_PING)) {
                FilePeerMsgQueue.add(filePeerMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("get a connection:" + ctx.channel().id());
        super.channelActive(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        try {
            DeviceServerFileWorker.sessionPool.removeSessionByChannelId(ctx.channel().id());
            System.out.println(ctx.channel().id() + "  caught exception server");
            ctx.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}